package com.ego.dubbo.service.impl;

import com.ego.commons.exception.DaoException;
import com.ego.dubbo.service.PassportDubboService;
import com.ego.mapper.TbUserMapper;
import com.ego.pojo.TbUser;
import com.ego.pojo.TbUserExample;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DubboService
public class PassportDubboServiceImpl implements PassportDubboService {

    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    public TbUser selectByTbUser(TbUser tbUser) {

        TbUserExample tbUserExample = new TbUserExample();
        TbUserExample.Criteria criteria = tbUserExample.createCriteria();

        if(StringUtils.isNotBlank(tbUser.getUsername())){
            criteria.andUsernameEqualTo(tbUser.getUsername());
        }else if(StringUtils.isNotBlank(tbUser.getEmail())){
            criteria.andEmailEqualTo(tbUser.getEmail());
        }else if(StringUtils.isNotBlank(tbUser.getPhone())){
            criteria.andPhoneEqualTo(tbUser.getPhone());
        }

        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);

        return tbUsers.size()==1?tbUsers.get(0):null;
    }


    @Transactional(rollbackFor = Exception.class)
    public int register(TbUser tbUser) throws DaoException {
        try {
            return tbUserMapper.insert(tbUser);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DaoException("新增用户失败");
        }
    }

    @Override
    public TbUser login(TbUser tbUser) {

        TbUserExample tbUserExample = new TbUserExample();
        TbUserExample.Criteria criteria = tbUserExample.createCriteria();
        criteria.andUsernameEqualTo(tbUser.getUsername());
        criteria.andPasswordEqualTo(tbUser.getPassword());

        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);

        return tbUsers.size()==1?tbUsers.get(0):null;
    }
}
